package com.antdant.controller;

import com.antdant.annotation.RequireLogin;
import com.antdant.common.GeneralResponse;
import com.antdant.entity.User;
import com.antdant.exception.GeneralException;
import com.antdant.service.LoginService;
import com.antdant.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author Lee Yunc
 * @Date 2021/2/23 14:28
 * @Description:
 * @Version 1.0
 */
@Slf4j
@RestController
public class LoginController extends BaseController {

    @Resource
    private LoginService loginService;

    /**
     * 登录
     *
     * @param user
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public GeneralResponse loginByLoginId(@RequestBody User user, HttpServletRequest request) {
        try {
            return success(loginService.login(IpUtils.getIP(request), user, IpUtils.getUserAgent(request)));
        } catch (GeneralException e) {
            log.error("login failed,error:", e);
            return failed(e.getMessage());
        } catch (Exception e) {
            log.error("login failed,error:", e);
            return failed("登录失败，请稍后重试！");
        }
    }

    /**
     * 已经登录的时候，通过token获取已经登录的用户信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getLoginUser")
    @RequireLogin
    public GeneralResponse getLoginUserInfo(HttpServletRequest request) {
        return success(getLoginUser(request));
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout")
    public GeneralResponse logout(HttpServletRequest request) {
        loginService.logout(request);
        return success("退出登录！");
    }

    /**
     * 忘记密码时发送验证码
     *
     * @param toEmail
     * @return
     */
    @RequestMapping(value = "/sendEmail")
    public GeneralResponse sendEmail(@RequestParam String toEmail) {
        return success("发送成功", loginService.sendVerifyCode(toEmail));
    }

    /**
     * 刷新token
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/refreshToken")
    public GeneralResponse refreshToken(HttpServletRequest request) {
        try {
            return success(loginService.refreshToken(request));
        } catch (Exception e) {
            log.error("login failed,error:", e);
            return failed("刷新失败，请稍后重试！");
        }
    }

}
